#ifndef __PROTOCOL_HPP__
#define __PROTOCOL_HPP__

#include <iostream>
#include <string>
#include <cstring>

#define SPACE " "
#define SPACE_LEN strlen(SPACE)
#define SEP "\r\n"
#define SEP_LEN strlen(SEP)

class Request
{
public:
    std::string Serialization()
    {
        std::string res;
        res+=std::to_string(_x);
        res+=SPACE;
        res+=_op;
        res+=SPACE;
        res+=std::to_string(_y);
        return res;
    }

    bool Deserialization(const std::string& str)
    {
        size_t left=str.find(SPACE);
        if(left==std::string::npos) return false;
        size_t right=str.rfind(SPACE);
        if(right==std::string::npos) return false;
        _x=atoi(str.substr(0,left).c_str());
        _y=atoi(str.substr(right+1).c_str());
        _op=str[left+1];
        return true;
    }

    Request()=default;

public:
    int _x;
    char _op;
    int _y;
};

class Response
{
public:
    std::string Serialization()
    {
        std::string res;
        res+=std::to_string(_code);
        res+=SPACE;
        res+=std::to_string(_result);
        return res;
    }

    void Deserialization(const std::string& str)
    {
        size_t pos=str.find(SPACE);
        if(pos==std::string::npos) return;
        _code=atoi(str.substr(0,pos).c_str());
        _result=atoi(str.substr(pos+SPACE_LEN).c_str());
        return;
    }

public:
    int _code=4;
    int _result;
};

std::string Decode(std::string& buffer)//解包
{
    size_t pos=buffer.find(SEP);
    if(pos==std::string::npos) return "";//没找到SEP
    int len=atoi(buffer.substr(0,pos).c_str());
    int remainLen=buffer.size()-2*SEP_LEN-pos;
    if(remainLen<len) return "";//内容长度不足
    
    //拆包
    buffer.erase(0,pos+SEP_LEN);
    std::string res=buffer.substr(0,len);
    buffer.erase(0,len+SEP_LEN);
    return res;
}

//length\r\n数据\r\n
std::string Encode(const std::string& buffer)//封包
{
    std::string messages=std::to_string(buffer.size());
    messages+=SEP;
    messages+=buffer;
    messages+=SEP;
    return messages;
}
#endif